<template>
    <div class="cpAllList">
        <div class="header">
            <van-nav-bar title="产品-全部" left-arrow @click-left="handleLeft" />
        </div>
        <div class="cpAllList_searc">
            <div class="cpAllList_searc_felx">
                <searchHome v-model:value="queryParams.content" placeholder="请输入商品名称/商品码或69码" @onSubmit="onRefresh"
                    :isFiltrate="false" />
            </div>
            <img src="@/assets/home/icon_shaixuan.png" alt="" @click="showTop = !showTop">
        </div>
        <div class="mongolian_layer" v-show="showTop" @click="">
            <div class="mongolian_layer_options">
                <div class="mongolian_layer_options_top">
                    <div class="title">到期时间</div>
                    <div class="date_shelf">
                        <div v-for="(item, index) in dataList" :key="index" class="date_shelf_div" @click="datePicker">
                            <van-image :src="complement" class="menu_cions" />
                            <div class="title">{{ computPlace(item, index) }}</div>
                        </div>
                        <div class="div">至</div>
                    </div>
                    <van-calendar v-model:show="pickerShow" type="range" @confirm="onConfirm" :allow-same-day="true"
                        :min-date="minDate" :max-date="maxDate" ref="calendarRef" />
                    <div class="title">产品部门</div>
                    <div class="shelf_type anthor_type">
                        <div @click="shelfClick(index, item.deptId)" v-for="(item, index) in shelfList" :key="index"
                            :class="shelfIndex !== index ? 'shelf_div' : 'shelf_div_avtive'">
                            {{ item.deptName }}
                        </div>
                    </div>
                    <div class="title">产品专员</div>
                    <div class="shelf_type anthor_type anthor_types">
                        <div v-for="(item, index) in recruiterList" :key="index" class="anthor_type_div">
                            <div @click="recruiterClick(index)"
                                :class="recruiterIndex !== index ? 'shelf_div' : 'shelf_div_avtive'">
                                {{ item.nickName }}
                            </div>
                        </div>
                    </div>
                </div>
                <div class="buttons">
                    <div class="reset" @click="reset">重置</div>
                    <div class="submit" @click="submit">完成</div>
                </div>
            </div>
            <div class="mongolian_layer_layer"></div>
        </div>
        <div class="cpAllList_box">
            <div class="box_screen">
                <div class="box_screen_div" @click="screenClicks()">
                    <div class="box_screen_child">{{ catName }}</div>
                    <van-image :src="heisexiasanjiao" class="box_screen_icons" />
                </div>
                <div class="box_screen_div" v-for="(item, index) in screenList" :key="index"
                    @click="screenClick(index)">
                    <div class="box_screen_child">{{ item.title }}</div>
                    <div class="box_screen_icon">
                        <img :src="computScreen(index)" alt="" class="box_screen_icons">
                        <img :src="computScreens(index)" alt="" class="box_screen_icons">
                    </div>
                </div>
                <div class="box_screen_div" @click="deptShow = true">
                    <div class="box_screen_child">{{ commodityName }}</div>
                    <van-image :src="heisexiasanjiao" class="box_screen_icons" />
                </div>
            </div>
            <!-- <div class="box_screen">
                筛选条件
            </div> -->
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh" style="flex: 1;min-height: 0;">
                <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                    <template v-slot:finished>
                        <div class="nothing_div" v-if="list.length == 0 && !refreshing">
                            <van-image :src="nothingData"></van-image>
                            <div class="nothing_font">暂无数据</div>
                        </div>
                    </template>
                    <div class="selectedProducts">
                        <ListLookCard type="2" v-for="item in list" :key="item.id" :datas="item"
                            @itemClick="routerGo(item.type, item.productId)" @onRefresh="onRefresh" />
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
        <category :isShow="isShow" @leftClick="leftClick" @onSubmit="onSubmit" v-model:value="queryParams.categoryIdList" :multiple="true" />
        <van-action-sheet title="商品状态" v-model:show="deptShow" :actions="deptList" @select="onSelectCategory" />
    </div>
</template>

<script setup lang="ts">
import { onActivated, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { type CalendarInstance } from 'vant';
import { getEnvValue } from "@/utils/index";
// api
import { getStickProductDept, getUserProductList } from '@/api/productHome/index'
import { selectOutList } from '@/api/operation/index'
// 组件
import searchHome from '@/views/productHome/productLists/components/searchHome/index.vue'
import ListLookCard from '../components/listLookCard/index.vue'
import category from '@/components/category/index.vue'
// 图片
import nothingData from '@/assets/porduct/icon_zanwushuju.png'
import heiseshangsanjiao from '@/assets/productHome/icon_heiseshangsanjiao.png'
import huiseshangsanjiao from '@/assets/productHome/icon_huiseshangsanjiao.png'
const complement = new URL("@/assets/productHome/icon_riqi.png", import.meta.url).href;
const heisexiasanjiao = new URL("@/assets/productHome/icon_heisexiasanjiao.png", import.meta.url).href;
const huisexiasanjiao = new URL("@/assets/productHome/icon_huisexiasanjiao.png", import.meta.url).href;

const router = useRouter()
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    content: '',
    categoryIdList: [],
    outTimeSort: 1,
    putStatus: '',
    cycleStartTime: '',
    cycleEndTime: '',
    stockDeptId: '',
    stockUserId: ''
});
const refreshing = ref(false);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)
const serchFlag = ref(true)
const loading = ref(false);
const finished = ref(false);
const list = ref<any[]>([]);
const catName = ref('商品类目')
const commodityName = ref('商品状态')
const isShow = ref<any>(false)
// 筛选集合
const screenList = ref([
    { title: '出库时间' },
])
// 筛选
const showTop = ref(false)
const dataList = ref([
    '起始时间', '结束时间'
])
// 日期展示
const pickerShow = ref(false)
// 开始时间
const startTime = ref()
// 结束时间
const endTime = ref()
// 自定义日期范围
const minDate = new Date('2010/01/01')
const maxDate = new Date('2050/12/31')
// 招商部 index
const shelfIndex = ref<any>()
// 招商部
const shelfList = ref<any>([])
// 招商员
const recruiterList = ref<any>([])
// 招商员 index
const recruiterIndex = ref()
// 日期ref
const calendarRef = ref<CalendarInstance>();
const deptShow = ref(false)
const deptList = ref([{
    name: '全部',
    status: ''
}, {
    name: '已归还',
    status: '1'
}, {
    name: '未归还',
    status: '2'
}, {
    name: '超期归还',
    status: '3'
}, {
    name: '超期未还',
    status: '4'
}])
/** 商品状态选择事件 */
const onSelectCategory = (selection) => {
    deptShow.value = false;
    commodityName.value = selection.name === '全部' ? '商品状态' : selection.name
    queryParams.value.putStatus = selection.status
    onRefresh()
}
/** 上架时间点击事件 */
const datePicker = () => {
    pickerShow.value = true
}
/** 日期回显 */
const computPlace = (item: string, index: number) => {
    if (index == 0) {
        if (startTime.value) {
            return startTime.value
        } else {
            return item
        }
    } else if (index == 1) {
        if (endTime.value) {
            return endTime.value
        } else {
            return item
        }
    }
}
const formatDate = (date) => `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
/** 日期选择 */
const onConfirm = (values) => {
    const [start, end] = values;
    pickerShow.value = false
    startTime.value = formatDate(start)
    endTime.value = formatDate(end)
}
/** 招商部点击 */
const shelfClick = async (index: number, deptId: string) => {
    if (shelfIndex.value == index) {
        shelfIndex.value = undefined
        recruiterList.value = []
        recruiterIndex.value = undefined
    } else {
        shelfIndex.value = index
        const res = await getUserProductList({ deptId: deptId })
        recruiterList.value = res.data
        recruiterIndex.value = undefined
    }
}
/** 招商员点击 */
const recruiterClick = (index: number) => {
    if (recruiterIndex.value == index) {
        recruiterIndex.value = undefined
    } else {
        recruiterIndex.value = index
    }
}
/** 获取招商部门 */
const getanchor = async () => {
    const res = await getStickProductDept()
    shelfList.value = res.data
}
getanchor()
/** 重置 */
const reset = () => {
    shelfIndex.value = undefined
    recruiterIndex.value = undefined
    startTime.value = undefined
    endTime.value = undefined
    calendarRef.value?.reset();
    queryParams.value = {
        pageNum: 1,
        pageSize: 10,
        content: '',
        categoryId: '',
        outTimeSort: 1,
        putStatus: '',
        // 商品状态  1 已还    2 未还   3 超期归还  4  超期为还
        cycleStartTime: '',
        cycleEndTime: '',
        stockDeptId: '',
        stockUserId: ''
    }
}
/** 完成 */
const submit = () => {
    // 招商部
    if (shelfIndex.value !== undefined && shelfIndex.value !== null && shelfIndex.value !== '') {
        queryParams.value.stockDeptId = shelfList.value[shelfIndex.value].deptId
    } else {
        queryParams.value.stockDeptId = undefined
    }
    // 招商员
    if (recruiterIndex.value !== undefined && recruiterIndex.value !== null && recruiterIndex.value !== '') {
        queryParams.value.stockUserId = recruiterList.value[recruiterIndex.value].userId
    } else {
        queryParams.value.stockUserId = undefined
    }
    // 日期
    queryParams.value.cycleStartTime = startTime.value
    queryParams.value.cycleEndTime = endTime.value
    showTop.value = false
    onRefresh();
}
/** 查询商品列表 */
const getList = async () => {
    refreFlag.value = false
    const res = await selectOutList(queryParams.value);
    setTimeout(() => {
        refreFlag.value = true
        // 空数据 停止加载
        if (res.rows.length == 0) {
            list.value = [];
            serchFlag.value = true;
            finished.value = true;
            return;
        }
        // 有数据 赋值列表 加载状态结束
        res.rows.forEach((item) => {
            finished.value = false;
            if (item.productImage) {
                item.productImages = getEnvValue("VITE_APP_PIC_URL") + item.productImage.split(',')[0];
            } else {
                item.productImages = "";
            }
            list.value.push(item);
        });
        loading.value = false;
        refreshing.value = false;
        serchFlag.value = true;
        // 如果list长度大于等于总数据条数，数据全部加载完成
        if (list.value.length >= res.total) {
            finished.value = true; //结束加载
        }
        // 解决快速切换tab导致的列表商品混乱问题
        if (queryParams.value.pageNum == 2 && queryParams.value.auditStatus) {
            list.value = list.value.filter((item) => {
                return item.auditStatus == queryParams.value.auditStatus
            })
        }

    }, 400);
};
/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        serchFlag.value = false
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};
/** 筛选点击事件 */
const screenClick = (index: number) => {
    if (index == 0) {
        if (queryParams.value.outTimeSort == '2') {
            queryParams.value.outTimeSort = '1'
        } else {
            queryParams.value.outTimeSort = '2'
        }
    }
    onRefresh();
}
/** 筛选上升点击事件 */
const computScreen = (index: number) => {
    if (index == 0) {
        if (queryParams.value.outTimeSort == '2') {
            return heiseshangsanjiao
        } else if ((queryParams.value.outTimeSort == '1')) {
            return huiseshangsanjiao
        } else {
            return huiseshangsanjiao
        }
    }
}
/** 筛选下降点击事件 */
const computScreens = (index: number) => {
    if (index == 0) {
        if (queryParams.value.outTimeSort == '2') {
            return huisexiasanjiao
        } else if (queryParams.value.outTimeSort == '1') {
            return heisexiasanjiao
        } else {
            return huisexiasanjiao
        }
    }
}
/** 商品类目 */
const screenClicks = () => {
    isShow.value = true
}
// 类目导航返回
const leftClick = () => {
    isShow.value = false
}
// 搜索查询
const onSubmit = () => {
    catName.value = queryParams.value.categoryIdList.length ? '多品类' : '商品类目'
    isShow.value = false
    onRefresh()
}

const handleLeft = () => {
    router.back()
}
// 跳转商品详情
const routerGo = (type: any, id: string) => {
    if (type == 1) {
        router.push({
            path: `/researchBasicsDetail/${id}`
        })
    } else {
        router.push({
            path: `/operationBasicsDetail/${id}`
        })
    }
}



const vantListScrollTop = ref<any>(0) // 滚动位置
// 在组件挂载完成后添加事件监听器
onMounted(async () => {
    functionScroll('init')
})
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    functionScroll('delete')
});
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
onActivated(() => {
    functionScroll('black')
})
</script>

<style lang="less" scoped>
.cpAllList {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    display: flex;
    background: #F6FAFF;
    flex-flow: column;
    position: relative;

    .header {
        background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .cpAllList_searc {
        display: flex;
        align-items: center;

        .cpAllList_searc_felx {
            flex: 1;
            min-width: 0;
        }

        img {
            width: 20px;
            height: 20px;
            margin: 0 15px 0 0;
        }
    }

    .mongolian_layer {
        width: 100%;
        height: calc(100vh - 150px);
        position: absolute;
        top: 150px;
        left: 0;

        .mongolian_layer_layer {
            width: 100%;
            height: calc(100% - 540px);
            position: absolute;
            z-index: 6000;
            background: #000000;
            opacity: 0.73;
            margin-top: 540px;
        }

        .mongolian_layer_options {
            width: 100%;
            height: 540px;
            display: flex;
            flex-flow: column;
            background: #FFFFFF;
            position: absolute;
            z-index: 6001;
            padding: 15px;
            box-sizing: border-box;

            .mongolian_layer_options_top {
                flex: 1;
                min-height: 0;
                overflow-y: auto;
                display: flex;
                flex-flow: column;

                .prices {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;
                    margin-bottom: 20px;
                    margin-top: 10px;
                    box-sizing: border-box;
                }

                .title {
                    width: 100%;
                }

                .titles {}

                .custom-button {
                    width: 24px;
                    height: 24px;
                    background-color: var(--van-primary-color);
                    border-radius: 24px;
                }

                .price_title {
                    position: absolute;
                    top: -20px;
                    left: -10px;
                }

                .price_titles {
                    width: 100px;
                    top: -20px;
                    position: absolute;
                }

                .price_pre {
                    width: 100%;
                    height: 115px;
                    display: flex;
                    align-items: center;
                    justify-content: flex-start;
                    flex-wrap: wrap;
                    margin-top: 20px;
                    align-content: space-between;
                    margin-bottom: 20px;

                    .price_pre_div {
                        width: calc(100% / 3) !important;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }

                    .price_div {
                        width: 108px;
                        height: 30px;
                        border-radius: 15px;
                        border: 1px solid #B8BECA;
                        font-weight: 400;
                        font-size: 14px;
                        color: #B8BECA;
                        text-align: center;
                        line-height: 30px;
                        box-sizing: border-box;
                    }

                    .price_div_avtive {
                        width: 108px;
                        height: 30px;
                        border-radius: 15px;
                        background: #0094FF;
                        font-weight: 400;
                        font-size: 14px;
                        color: #fff;
                        text-align: center;
                        line-height: 30px;
                    }
                }

                .anthor_type {
                    height: auto !important;
                    flex-wrap: wrap;

                    .anthor_type_div {
                        width: calc(100% / 3) !important;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }

                    .shelf_div {
                        margin-bottom: 10px;
                        width: 108px !important;
                    }

                    .shelf_div_avtive {
                        margin-bottom: 10px;
                        width: 108px !important;
                    }


                }

                .anthor_types {
                    justify-content: flex-start !important;
                }

                .shelf_type {
                    width: 100%;
                    height: 30px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-top: 20px;
                    margin-bottom: 20px;

                    .shelf_div {
                        width: 78px;
                        height: 30px;
                        border-radius: 15px;
                        border: 1px solid #B8BECA;
                        font-weight: 400;
                        font-size: 14px;
                        color: #B8BECA;
                        text-align: center;
                        line-height: 30px;
                        box-sizing: border-box;
                    }

                    .shelf_div_avtive {
                        width: 78px;
                        height: 30px;
                        border-radius: 15px;
                        background: #0094FF;
                        font-weight: 400;
                        font-size: 14px;
                        color: #fff;
                        text-align: center;
                        line-height: 30px;
                    }
                }

                .date_shelf {
                    width: 100%;
                    height: 34px;
                    display: flex;
                    position: relative;
                    justify-content: space-between;
                    align-items: center;
                    margin-top: 20px;
                    margin-bottom: 20px;

                    .date_shelf_div {
                        width: 159px;
                        height: 34px;
                        border-radius: 17px;
                        border: 1px solid #B8BECA;
                        position: relative;
                        text-align: center;
                        line-height: 34px;

                        .menu_cions {
                            position: absolute;
                            width: 14px;
                            height: 14px;
                            top: 10px;
                            left: 15px;
                        }

                        .title {
                            font-weight: 400;
                            font-size: 14px;
                            color: #B8BECA;
                        }
                    }

                    .div {
                        position: absolute;
                        left: 50%;
                        top: 50%;
                        transform: translate(-50%, -50%);
                    }
                }
            }


            .buttons {
                width: 100%;
                height: 44px;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .reset {
                    width: 162px;
                    height: 44px;
                    border-radius: 23px;
                    border: 1px solid #0094FF;
                    text-align: center;
                    line-height: 44px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #0094FF;
                }

                .submit {
                    width: 162px;
                    height: 44px;
                    border-radius: 23px;
                    background: #0094FF;
                    text-align: center;
                    line-height: 44px;
                    font-weight: 400;
                    font-size: 14px;
                    color: #fff;
                }
            }
        }
    }

    .cpAllList_box {
        flex: 1;
        min-height: 0;
        background: #fff;
        display: flex;
        flex-flow: column;

        .box_screen {
            display: flex;
            align-items: center;
            justify-content: space-around;
            box-sizing: border-box;
            height: 44px;
            width: 100%;
            line-height: 44px;
            background-color: #fff;
            padding: 0 20px;

            .box_screen_div {
                display: flex;
                align-items: center;
                display: flex;
                justify-content: center;

                .box_screen_icons {
                    width: 10px;
                    height: 6px;
                    margin-left: 5px;
                }

                .box_screen_child {
                    font-weight: 400;
                    font-size: 14px;
                    color: #1A1B1C;
                }

                .box_screen_icon {
                    display: flex;
                    flex-wrap: wrap;
                    width: 10px;
                    height: 16px;
                    margin-left: 5px;

                    .box_screen_icons {
                        width: 10px;
                        height: 6px;
                    }
                }
            }
        }

        .selectedProducts {
            width: 100%;
            box-sizing: border-box;
            padding: 0 10px 10px;
        }
    }
}

:deep(.van-pull-refresh) {
    overflow: scroll;
}
</style>